package com.jahentao.testcase;


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 默认的命令行编译器
 * @author jahentao
 * @version 1.0
 * @created 26-5月-2017 18:03:39
 */
public class DefaultCLICompiler extends CLITemplate {

    /**
     * 源代码文件名
     */
    private File sourceFile;

    public void setSourceFile(File sourceFile) {
        this.sourceFile = sourceFile;
    }

    public DefaultCLICompiler() throws IOException {
        super();
    }

	public DefaultCLICompiler(File sourceFile) throws IOException {
	    super();
	    this.sourceFile = sourceFile;
	    super.command = piece();
	}

    /**
     * 拼凑命令行编译指令
     * @return 命令行编译指令
     */
	private String piece(){
        StringBuffer buffer = new StringBuffer();
        buffer.append("\"").append(getCompiler()).append("\" \"").append(getCorrSource()).append(sourceFile.getName())
                .append("\" -o \"").append(getOutputDir()).append(sourceFile.getName().substring(0,sourceFile.getName().length()-3)).append("exe\"")
                .append(" -g3 ");
        for (String include : getIncludes()) {
            buffer.append("-I\"").append(include).append("\" ");
        }
        for (String lib : getLibs()) {
            buffer.append("-L\"").append(lib).append("\" ");
        }
        buffer.append("-static-libgcc -g3");
	    return buffer.toString();
    }

    /**
	 * 编译
	 * 
	 * @param command    命令行编译指令
	 */
	public void compile(String command){
	    if (command==null)
	        command = piece();
	    else {
	        // 获取运行时环境，进行编译
            // 调用命令行接口
            Process pr = null;
            BufferedReader in = null;
            try {
                pr = Runtime.getRuntime().exec(command);
                // 获得命令行输出
                in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                }
                pr.waitFor();// 等待返回值 不为0是非正常
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
	}

}